import axios from 'axios';
import { MessageBox, Message } from 'element-ui';
import store from '@/store';
import i18n from '@/lang'
import router from '@/router';
import { getToken } from '@/utils/auth';

// create an axios instance
const service = axios.create({
    baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
    withCredentials: true, // send cookies when cross-domain requests
    timeout: 30000 // request timeout
});

// request interceptor
service.interceptors.request.use(
    config => {
        // do something before request is sent

        /* if (store.getters.token) {
            // let each request carry token
            // ['X-Token'] is a custom headers key
            // please modify it according to the actual situation
            // config.headers['X-Token'] = getToken()
        }*/
        return config;
    },
    error => {
        // do something with request error
        console.log(error); // for debug
        return Promise.reject(error);
    }
);

// response interceptor
service.interceptors.response.use(
    response => {
        const res = response.data;
        // if the custom code is not 20000, it is judged as an error.
        if (!res.success) {
            console.warn('接口返回错误', response);
            // 5011 登录过期未登录;
            if (res.code === 5011) {
                // to re-login
                /*Message({
                    message: i18n.t('login.noLogin'), // error.response.data.message,
                    type: 'error',
                    duration: 5 * 1000
                });*/
            } else {
                /*Message({
                    message: i18n.t('tips.reqExcp'), // error.response.data.message,
                    type: 'error',
                    duration: 5 * 1000
                });*/
            }
            return Promise.reject(res.message || 'Error');
        } else {
            return res;
        }
    },
    error => {
        console.warn('接口错误：', error.response);
        console.log('err' + error); // for debug
        if (error.response.status === 511) {
            // 重新登录
            MessageBox.confirm(error.response.data.message, i18n.t('global.hint'), {
                confirmButtonText: i18n.t('login.reLogin'),
                cancelButtonText: i18n.t('global.cancel'),
                customClass: 'custom-msgbox',
                center: true
            }).then(() => {
                store.dispatch('user/resetToken').then(() => {
                    location.reload();
                });
            });
        } else {
            /*Message({
                message: 'Request exception', // error.response.data.message,
                type: 'error',
                duration: 5 * 1000
            });*/
        }
        return Promise.reject(error.response.data.message);
    }
);

export default service;
